<?php
/**
 * Created by PhpStorm.
 * User: Machenike
 * Date: 2019/9/16
 * Time: 16:57
 */

namespace App\Project;


use App\Base\BaseModel;
use App\Model\ApiMoneyConfigModel;
use App\Model\ApiUserModel;
use App\Model\ApiUserStaticModel;

class ShengJinModel extends BaseModel
{

    /**
     * @param $projectId
     * @param $user
     * @return array[vip_num,yj_my+yj_team,yj_my,yj_team]
     */
    public function getTeamCondition($projectId,$user)
    {
        //获取本人业绩
        $ApiUserStaticModel = new ApiUserStaticModel($this->getDoctrine());
        $static = $ApiUserStaticModel->getUser($projectId,$user,1,205);
        $yj_my =  $static->getNum();

        //获取团队业绩
        $static = $ApiUserStaticModel->getUser($projectId,$user,1,301);
        $yj_team =  $static->getNum();

        //获取本人推荐的VIP人数
        $ApiUserModel = new ApiUserModel($this->getDoctrine());
        $vip_num = $ApiUserModel->countMyVipSon($projectId,$user);
        return [$vip_num,$yj_my+$yj_team,$yj_my,$yj_team];
    }

    public function checkAndLevelUp($projectId,$user){
        //获取升级规则的数据
        $ApiMoneyConfigModel = new ApiMoneyConfigModel($this->getDoctrine());
        $conf = $ApiMoneyConfigModel->getByCode($projectId,"LEVEL_UP_CONDITION");
        $level = $this->myExplodeNumbers($conf->getV());
        $levelSetting = [];
        foreach ($level as $key => $value) {
            $level = floor($key/2) + 1;
            if ($key%2 == 0) {
                $levelSetting[$level]["vip"]= $value;
            }else{
                $levelSetting[$level]["money"]= $value;
            }
        }
        var_dump($levelSetting);

        //获取用户当前数据
        $cond = $this->getTeamCondition($projectId,$user);
        $vipNum = $cond[0];
        $totalMoney = $cond[1];
        $curLevel = false;
        foreach ($levelSetting as $level=>$setting) {
            if ($vipNum >= $setting["vip"] && $totalMoney >= $setting["money"] ) {
                $curLevel = $level;
            }
        }
        if ($curLevel !== false) {
            //找到了新的等级区间
            //更新用等级信息
            $ApiUserModel = new ApiUserModel($this->getDoctrine());
            $userEntity =  $ApiUserModel->getUser($projectId,$user);
            $userEntity->setCat($level);
            $this->em->persist($userEntity);$this->em->flush();
        }


        return false;
    }
}